package com.webchat.user.service;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.webchat.common.enums.RedisKeyEnum;
import com.webchat.common.enums.RoleCodeEnum;
import com.webchat.common.service.RedisService;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.response.publicaccount.PublicAccountVO;
import com.webchat.user.repository.dao.IUserDAO;
import com.webchat.user.repository.entity.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PublicAccountService {

    @Autowired
    private IUserDAO userDAO;

    @Autowired
    private RedisService redisService;


    /**
     * 查询全部公众号列表
     *
     * @return
     */
    public List<PublicAccountVO> getPublicAccountListFromCache() {
        String key = RedisKeyEnum.PUBLIC_ACCOUNT_LIST_CACHE.getKey();
        String cache = redisService.get(key);
        if (StringUtils.isNotBlank(cache)) {
            return JsonUtil.fromJson(cache, new TypeReference<List<PublicAccountVO>>() { });
        }
        return this.refreshPublicAccountListCache();
    }

    /**
     * 刷新公众号列表缓存
     *
     * @return
     */
    public List<PublicAccountVO> refreshPublicAccountListCache() {
        String key = RedisKeyEnum.PUBLIC_ACCOUNT_LIST_CACHE.getKey();
        List<UserEntity> list = userDAO.findAllByRoleCodeOrderByIdDesc(RoleCodeEnum.PUBLIC_ACCOUNT.getCode());
        List<PublicAccountVO> accountList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            accountList = list.stream().map(e -> {
                PublicAccountVO publicAccount = new PublicAccountVO();
                publicAccount.setId(e.getUserId());
                publicAccount.setName(e.getUserName());
                publicAccount.setPhoto(e.getPhoto());
                return publicAccount;
            }).collect(Collectors.toList());
        }
        redisService.set(key, JsonUtil.toJsonString(accountList), RedisKeyEnum.PUBLIC_ACCOUNT_LIST_CACHE.getExpireTime());
        return accountList;
    }
}
